<template>
  <div>
    <div v-if="mode === 'DESIGN'">
      <div class="design">
        <i class="el-icon-plus"></i>
      </div>
     <!-- <p>{{ placeholder }} {{ sizeTip }}</p> -->
     <p>{{ placeholder }}</p>
    </div>
    <div v-else>
      <el-upload
        :file-list="fileList"
        action=""
        :limit="maxSize"
        with-credentials
        :multiple="maxSize > 0"
        :data="{biz:bizPath}"
        list-type="picture-card"
        :http-request="uploadHandle"
        :on-change="successUpload"
        :class="{'hide': disabled}"
        >
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{ file }">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
              <i class="el-icon-download"></i>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>

       <!-- <div slot="tip" class="el-upload__tip">{{ placeholder }} {{ sizeTip }}</div> -->
      </el-upload>
    </div>
    <el-dialog :visible.sync="dialogVisible" append-to-body width="40%">
      <div style="text-align: center;">
        <img width="60%" :src="dialogImageUrl" alt="">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import componentMinxins from '../ComponentMinxins';  
import {  downloadFileBlob } from '@/utils/wflow/index';
import { uploadAction, getFileAccessHttpUrl,downloadFile } from '@/api/manage'
 const uidGenerator=()=>{
    return '-'+parseInt(Math.random()*10000+1,10);
  }
 const getFileName=(path)=>{
    if(path.lastIndexOf("\\")>=0){
      let reg=new RegExp("\\\\","g");
      path = path.replace(reg,"/");
    }
    return path.substring(path.lastIndexOf("/")+1);
  }
export default {
  mixins: [componentMinxins],
  name: 'ImageUpload',
  components: {},
  props: {
    mode:{
      type: String,
      default: 'DESIGN'
    },
    required:{
      type: Boolean,
      default: false
    },
    value:{
      type:[String,Array],
      required:false
    },
    /*这个属性用于控制文件上传的业务路径*/
    bizPath:{
      type:String,
      required:false,
      default:"temp"
    },
    placeholder: {
      type: String,
      default: '请选择图片',
    },
    maxSize: {
      type: Number,
      default: 10,
    },
    maxNumber: {
      type: Number,
      default: 10,
    },
    enableZip: {
      type: Boolean,
      default: true,
    },
    disabled:{
      type:Boolean,
      default:false
    },
  },
  computed: {
    sizeTip() {
      return this.maxSize > 0 ? `| 每张图不超过${this.maxSize}MB` : '';
    },
  },
  data() {
    return {
      headers:{},
      uploadParams: {},
      fileList:[],   //文件上传列表
      urlList:[],   //只存放url的list
      dialogVisible:false,
      dialogImageUrl:null,
    };
  },
  //监听filelist
  watch:{
    value: {
      handler(val,oldValue) {
        if (val instanceof Array) {
          this.initFileList(val.join(','))
        } else {
          this.initFileList(val)
        }
        if(!val || val.length==0){
          this.picUrl = false;
        }
      },
      //立刻执行handler
      immediate: true
    }

  },
  methods: {
    //初始图片列表
    initFileList(paths){
      if(!paths || paths.length==0){
        this.fileList = [];
        return;
      }
      this.picUrl = true;
      let fileList = [];
      let arr = paths.split(",")
      for(var a=0;a<arr.length;a++){
        let url = getFileAccessHttpUrl(arr[a]);
        fileList.push({
          uid: uidGenerator(),
          name: getFileName(arr[a]),
          status: 'done',
          url: url
        })
      }
      this.fileList = fileList
    },
    //上传前判断类型和大小  
    beforeUpload(file) {
      const alows = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
      if (alows.indexOf(file.type) === -1) {
        this.$message.warning('存在不支持的图片格式');
      } else if (this.maxSize > 0 && file.size / 1024 / 1024 > this.maxSize) {
        this.$message.warning(`单张图片最大不超过 ${this.maxSize}MB`);
      } else {
        
        return true;
      }
      return false;
    },
     // 覆盖默认的上传行为
    uploadHandle(data){
      if(data.file){
        //上传文件的需要formdata类型;所以要转
        let FormDatas = new FormData();
        FormDatas.append('file', data.file);
        uploadAction(window._CONFIG['domianURL'] + '/file/upload', FormDatas).then((res) => {
          if (res.success) {
            // this.urlList=[]
            let urlList=[]
            if(res.message){
              this.fileList.push({name:data.file.name,url:res.message,uid: uidGenerator()})
              if(this.fileList && this.fileList.length > 0){
                this.fileList.forEach((item)=>{
                   urlList.push(item.url)
                })
                this.$emit('change',urlList.join(','))
                this._value = urlList.join(',')
              }else{
                this.$emit('change',null)
                 this._value = null
              }
            }else{
              this.$message.warning(res.message);
            }
          } 
        })
      }
    },
    //上传成功
    successUpload(file, fileList){
      console.log(file, fileList);
    },
    //删除
    handleRemove(file, fileList) {
      const fileData = this.fileList
      let urlList = []
      if(file){
        const index = fileData.findIndex((s)=>s.url === file.url)
        this.fileList.splice(index,1)
        if(this.fileList && this.fileList.length > 0){
          this.fileList.forEach((item)=>{
             urlList.push(item.url)
          })
          this.$emit('change',urlList.join(','))
        }
      }
    },
    //预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //下载
    handleDownload(file) {
      var a = document.createElement('a')
      a.href = this.fileUrl       
      a.download = this.fileUrl        
      a.target = '_blank'; 
      a.style.display = 'none'          
      document.body.appendChild(a)       
      a.click()                         
      a.remove() 
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
};
</script>

<style lang="less" scoped>
.design {
  i {
    padding: 10px;
    font-size: xx-large;
    background: white;
    border: 1px dashed #8c8c8c;
  }
}
::v-deep .el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 87px;
}
::v-deep .el-upload-list__item div{
  position: static;
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;  
}
::v-deep .el-upload-list--picture-card .el-upload-list__item-thumbnail{
  position: static;
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;  
}
/deep/ .el-upload-list__item {
  width: 80px;
  height: 80px;
  .el-upload-list__item-actions {
    & > span + span {
      margin: 1px;
    }
  }
}

.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}
::v-deep.hide .el-upload--picture-card {
  display: none;
}

</style>
